package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.product.ProductDirectoryListRequest;
import com.mes.cloud.api.dto.request.product.ProductDirectoryPageRequest;
import com.mes.cloud.api.dto.request.product.ProductDirectoryRequest;
import com.mes.cloud.api.dto.response.product.ProductDirectoryDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.ProductDirectoryDao;
import com.mes.cloud.entity.ProductDirectory;
import com.mes.cloud.entity.vo.ProductDirectoryVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 产品目录
 *
 * @author ysd
 * @version 2019-08-20 16:23:41
 * @email shaodong.yuan@pactera.com
 */
@Service
public class ProductDirectoryService {

    private ProductDirectoryDao productDirectoryDao;
    private IPKeyGenerator iPKeyGenerator;

    private SysCodeGeneratorService sysCodeGeneratorService;

    @Autowired
    public ProductDirectoryService(ProductDirectoryDao productDirectoryDao,
                                   SysCodeGeneratorService sysCodeGeneratorService,
                                   IPKeyGenerator iPKeyGenerator) {
        this.productDirectoryDao = productDirectoryDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.sysCodeGeneratorService = sysCodeGeneratorService;
    }

    /**
     * 分页查列表
     *
     * @param pageRequest
     * @return JsonResult
     */
    public JsonResult<CommPager<ProductDirectoryDto>> pageList(ProductDirectoryPageRequest pageRequest) {
        Page<ProductDirectoryDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        List<ProductDirectoryVo> productDirectoryList = productDirectoryDao.findPageListProductDirectory(pageRequest);

        List<ProductDirectoryDto> productDirectoryDtoList = new ArrayList<>();
        for (ProductDirectoryVo productDirectory : productDirectoryList) {
            ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
            BeanUtils.copyProperties(productDirectory, productDirectoryDto);
            productDirectoryDtoList.add(productDirectoryDto);
        }
        CommPager<ProductDirectoryDto> pageResult = new CommPager<>(page, productDirectoryDtoList);
        JsonResult<CommPager<ProductDirectoryDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 查询所有
     *
     * @param productDirectoryListRequest
     * @return JsonResult
     */
    public JsonResult<List<ProductDirectoryDto>> list(ProductDirectoryListRequest productDirectoryListRequest) {
        //查询条件
        ProductDirectoryVo selectParam = new ProductDirectoryVo();
        BeanUtils.copyProperties(productDirectoryListRequest, selectParam);
        //引用获取启用状态的数据
        selectParam.setEnableFlag(Constants.ENABLE_FLAG_YES);
        List<ProductDirectoryVo> productDirectoryList = productDirectoryDao.findALLProductDirectory(selectParam);

        List<ProductDirectoryDto> productDirectoryDtoList = new ArrayList<>();
        for (ProductDirectoryVo productDirectory : productDirectoryList) {
            ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
            BeanUtils.copyProperties(productDirectory, productDirectoryDto);
            productDirectoryDtoList.add(productDirectoryDto);
        }
        JsonResult<List<ProductDirectoryDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(productDirectoryDtoList);
        return jsonResult;
    }

    /**
     * 查询_编辑_产品目录树
     *
     * @param id
     * @return JsonResult
     */
    public JsonResult<List<ProductDirectoryDto>> updateTree(String id) {
        //查询_编辑_产品目录树
        List<ProductDirectoryVo> productDirectoryList = productDirectoryDao.findUpdateTreeProductDirectory(id);
        List<ProductDirectoryDto> productDirectoryDtoList = new ArrayList<>();
        for (ProductDirectoryVo productDirectory : productDirectoryList) {
            ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
            BeanUtils.copyProperties(productDirectory, productDirectoryDto);
            productDirectoryDtoList.add(productDirectoryDto);
        }
        JsonResult<List<ProductDirectoryDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(productDirectoryDtoList);
        return jsonResult;
    }

    /**
     * 新增
     *
     * @param productDirectoryRequest
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<ProductDirectoryDto> add(ProductDirectoryRequest productDirectoryRequest) {
        JsonResult jsonResult = new JsonResult();
        ProductDirectory productDirectory = new ProductDirectory();
        BeanUtils.copyProperties(productDirectoryRequest, productDirectory);

        //相同上级目录下，同级目录名称不能重复
        ProductDirectory selectParam = new ProductDirectory();
        selectParam.setParentId(productDirectoryRequest.getParentId());
        selectParam.setName(productDirectoryRequest.getName());
        int i = productDirectoryDao.selectCount(selectParam);
        if (i >= Constants.PRODUCT_DIRECTORY_NAME_COUNT) {
            jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_NAME_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_NAME_ERROR.getCode());
            return jsonResult;
        }
        //父节点是0，数据为母品牌目录
        if (Constants.CHANNEL_DIRECTORY_PARENTID.equals(productDirectory.getParentId())) {
            productDirectory.setModuleLevel(1);
        } else {
            //上级目录详情
            ProductDirectoryVo productDirectoryVo = productDirectoryDao.selectProductDirectoryDetails(productDirectory.getParentId());
            //品牌类型（只能新增竞品品牌）
            if (StringUtils.isNotEmpty(productDirectoryVo.getClassification())
                    && !Constants.PRODUCT_BRAND_TYPE.equals(productDirectoryVo.getClassification())) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_BRANDTYEPE_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_BRANDTYEPE_ERROR.getCode());
                return jsonResult;
            }
            //产品目录树最高七级
            if (productDirectoryVo.getModuleLevel() + 1 > Constants.PRODUCT_DIRECTORY_MODULELEVEL_MAX) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_MODULELEVEL_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_MODULELEVEL_ERROR.getCode());
                return jsonResult;
            }
            //类型为品牌,品牌ID不为空
            if (StringUtils.isNotEmpty(productDirectory.getBrandId()) && Constants.PRODUCT_DIRECTORY_TYPE.equals(productDirectory.getType())) {
                //父节点存在品牌
                List<ProductDirectoryVo> directoryPatent = productDirectoryDao.selectProductDirectoryParentList(productDirectory.getParentId());
                if (directoryPatent.get(0) != null) {
                    jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_FAMILY_DIRECTORY_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_FAMILY_DIRECTORY_ERROR.getCode());
                    return jsonResult;
                }
            } else {
                productDirectory.setBrandId(null);
            }
            productDirectory.setModuleLevel(productDirectoryVo.getModuleLevel() + 1);
        }
        productDirectory.setId(iPKeyGenerator.getGenerateKey());
        productDirectory.setCode(sysCodeGeneratorService.getCode(Constants.PRODUCT_DIRECTORY_PREFIX));
        productDirectory.setUpdateDateStr(DateUtil.updateDateStr());
        productDirectory.setCreateBy(UserUtil.getCreateByName());
        productDirectory.setUpdateBy(UserUtil.getUpdateByName());
        productDirectory.setCreateByNo(UserUtil.getCreateByNo());
        productDirectory.setUpdateByNo(UserUtil.getUpdateByNo());
        int count = productDirectoryDao.insertSelective(productDirectory);

        //响应返回值
        ProductDirectoryVo productDirectoryVo = productDirectoryDao.selectProductDirectoryDetails(productDirectory.getId());
        ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
        BeanUtils.copyProperties(productDirectoryVo, productDirectoryDto);

        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(productDirectoryDto);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 更新
     *
     * @param productDirectoryRequest
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<ProductDirectoryDto> update(ProductDirectoryRequest productDirectoryRequest) throws Exception {
        JsonResult jsonResult = new JsonResult();

        ProductDirectory productDirectory = new ProductDirectory();
        BeanUtils.copyProperties(productDirectoryRequest, productDirectory);

        //相同上级目录下，同级目录名称不能重复
        ProductDirectory selectParam = new ProductDirectory();
        selectParam.setParentId(productDirectoryRequest.getParentId());
        selectParam.setName(productDirectoryRequest.getName());
        int i = productDirectoryDao.selectCount(selectParam);
        if (i > Constants.PRODUCT_DIRECTORY_NAME_COUNT) {
            jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_NAME_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_NAME_ERROR.getCode());
            return jsonResult;
        }
        //父节点为全部
        if (Constants.CHANNEL_DIRECTORY_PARENTID.equals(productDirectory.getParentId())) {
            //品类类型是1
            if (!Constants.PRODUCT_DIRECTORY_TYPE_1.equals(productDirectory.getType())) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_PARENT_TYPE_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_PARENT_TYPE_ERROR.getCode());
                return jsonResult;
            }
            productDirectory.setModuleLevel(1);
        } else {
            //父节点详情
            ProductDirectory productDire = productDirectoryDao.selectByPrimaryKey(productDirectory.getParentId());
            //产品目录树最高七级
            if ((productDire.getModuleLevel() + 1 > Constants.PRODUCT_DIRECTORY_MODULELEVEL_MAX)) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_MODULELEVEL_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_MODULELEVEL_ERROR.getCode());
                return jsonResult;
            }
            productDirectory.setModuleLevel(productDire.getModuleLevel() + 1);
            //家族目录：父节点的家族目录+父节点名称
            productDirectory.setFamilyDirectory(productDire.getSelfDirectory());
            //自身目录：父节点的自身目录+当前节点名称
            productDirectory.setSelfDirectory(productDire.getSelfDirectory() + " / " + productDirectory.getName());
            //父级组：父节点的父级组 + 父节点的Id
            productDirectory.setFamilyDirectoryIds(productDire.getFamilyDirectoryIds() + " / " + productDire.getId());
        }
        //当前节点原数据
        ProductDirectoryVo directory = productDirectoryDao.selectProductDirectoryDetails(productDirectory.getParentId());
        //更新数据：品类为品牌、相关品牌不为空
        if (StringUtils.isNotEmpty(productDirectory.getBrandId()) && Constants.PRODUCT_DIRECTORY_TYPE.equals(productDirectory.getType())) {
            //原数据：所有子节点有相关品牌
            List<ProductDirectoryVo> directoryLast = productDirectoryDao.selectProductDirectoryLastList(productDirectory.getId());
            //原数据：所有父节点有相关品牌
            List<ProductDirectoryVo> directoryPatent = productDirectoryDao.selectProductDirectoryParentList(productDirectory.getParentId());
            if (directoryPatent.get(0) != null || directoryLast.get(0) != null) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_FAMILY_DIRECTORY_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_FAMILY_DIRECTORY_ERROR.getCode());
                return jsonResult;
            }
        } else {
            //非品牌目录，brandId为空
            productDirectory.setBrandId(null);
        }
        //修改目录状态，判断关联品牌类型（欣和品牌不允许修改）
        if (Constants.ENABLE_FLAG_NO.equals(productDirectory.getEnableFlag())
                && !Constants.PRODUCT_BRAND_TYPE.equals(directory.getClassification())) {
            jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_BRAND_TYPE_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_BRAND_TYPE_ERROR.getCode());
            return jsonResult;
        }

        productDirectory.setUpdateDateStr(DateUtil.updateDateStr());
        productDirectory.setUpdateBy(UserUtil.getUpdateByName());
        productDirectory.setUpdateByNo(UserUtil.getUpdateByNo());
        int count = productDirectoryDao.updateByPrimaryKeySelective(productDirectory);

        //响应返回值
        ProductDirectoryVo productDirectoryVo = productDirectoryDao.selectProductDirectoryDetails(productDirectory.getId());
        ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
        BeanUtils.copyProperties(productDirectoryVo, productDirectoryDto);

        if (count == 1) {
            batchUpdate(productDirectory);
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(productDirectoryDto);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    //更新关联子数据目录信息
    private void batchUpdate(ProductDirectory productDirectory) throws Exception {
        //查询启用状态子节点数
        ProductDirectory selectParam = new ProductDirectory();
        selectParam.setParentId(productDirectory.getId());
        List<ProductDirectory> select = productDirectoryDao.select(selectParam);
        if (select.size() > 0) {
            for (ProductDirectory productDire : select) {
                //家族目录
                productDire.setFamilyDirectory(productDirectory.getFamilyDirectory() + " / " + productDirectory.getName());
                //父级组
                productDire.setFamilyDirectoryIds(productDirectory.getFamilyDirectoryIds() + "," + productDire.getParentId());
                //自身目录
                productDire.setSelfDirectory(productDirectory.getFamilyDirectory() + " / " + productDirectory.getName() + " / " + productDire.getName());

                //产品目录树最高七级
                if (productDirectory.getModuleLevel() + 1 > Constants.PRODUCT_DIRECTORY_MODULELEVEL_MAX) {
                    throw new BaseException(HttpStatusEnum.BASE_CHANNEL_MODULELEVEL_ERROR.getCode(), HttpStatusEnum.BASE_CHANNEL_MODULELEVEL_ERROR.getMessage());
                }
                productDire.setModuleLevel(productDirectory.getModuleLevel() + 1);
                productDirectoryDao.updateByPrimaryKeySelective(productDire);
                batchUpdate(productDire);
            }
        }
    }

    /**
     * 查看详情
     *
     * @param id
     * @return JsonResult
     */
    public JsonResult<ProductDirectoryDto> get(String id) {
        JsonResult jsonResult = new JsonResult();
        ProductDirectoryVo productDirectory = productDirectoryDao.selectProductDirectoryDetails(id);
        if (productDirectory == null) {
            return jsonResult.setCode(HttpStatusEnum.RECORD_NOT_EXIST.getCode()).setMsg(HttpStatusEnum.RECORD_NOT_EXIST.getMessage());
        }
        ProductDirectoryDto productDirectoryDto = new ProductDirectoryDto();
        BeanUtils.copyProperties(productDirectory, productDirectoryDto);
        return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(productDirectoryDto);
    }

    /**
     * 禁用启用
     *
     * @param id
     * @param enableFlag
     * @return JsonResult
     */
    public JsonResult updateEnableFlag(String id, String enableFlag) {
        JsonResult jsonResult = new JsonResult();
        ProductDirectory productDirectory = new ProductDirectory();

        //是否禁用
        if (Constants.ENABLE_FLAG_NO.equals(enableFlag)) {
            ProductDirectory selectParam = new ProductDirectory();
            selectParam.setParentId(id);
            selectParam.setEnableFlag(Constants.ENABLE_FLAG_YES);
            int count2 = productDirectoryDao.selectCount(selectParam);
            //是否有子节点
            if (count2 > 0) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_ENABLEFLAG_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_ENABLEFLAG_ERROR.getCode());
                return jsonResult;
            }
            //是否已关联产品
            Integer productCount = productDirectoryDao.selectProductByDirectoryId(id);
            if (productCount > 0) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_PRODUCT_COUNT_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_PRODUCT_COUNT_ERROR.getCode());
                return jsonResult;
            }
            ProductDirectoryVo productDirectoryVo = productDirectoryDao.selectProductDirectoryDetails(id);
            //是否是竞品
            if (StringUtils.isNotEmpty(productDirectoryVo.getClassification()) && !Constants.PRODUCT_BRAND_TYPE.equals(productDirectoryVo.getClassification())) {
                jsonResult.setMsg(HttpStatusEnum.PRODUCT_DIRECTORY_BRAND_TYPE_ERROR.getMessage()).setCode(HttpStatusEnum.PRODUCT_DIRECTORY_BRAND_TYPE_ERROR.getCode());
                return jsonResult;
            }
        }
        productDirectory.setId(id);
        productDirectory.setEnableFlag(enableFlag.toString());
        int count = productDirectoryDao.updateByPrimaryKeySelective(productDirectory);

        if (count == 1) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    public int getCount(ProductDirectoryRequest productDirectoryRequest) {
        //查询条件
        ProductDirectory selectParam = new ProductDirectory();
        BeanUtils.copyProperties(productDirectoryRequest, selectParam);
        //引用获取启用状态的数据
        selectParam.setEnableFlag(Constants.ENABLE_FLAG_YES);
        return productDirectoryDao.selectCount(selectParam);
    }
}
